#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
密码分享相关路由
"""
import secrets
from datetime import datetime
from fastapi import APIRouter, Request, Form, HTTPException
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates

from ..database import get_db_connection, row_to_dict, rows_to_dict_list
from ..utils.config import config
from ..utils.security import hash_password
from ..auth.session import get_current_user, verify_user, verify_admin

router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get("/shares", response_class=HTMLResponse)
async def user_shares(request: Request):
    """用户分享页面"""
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login", status_code=302)
    
    return templates.TemplateResponse("shared_shares.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_short'),
        "user": user
    })


@router.get("/admin/shares", response_class=HTMLResponse)
async def admin_shares(request: Request):
    """管理员分享管理页面"""
    try:
        user = verify_admin(request)
    except HTTPException:
        return RedirectResponse(url="/login", status_code=302)
    
    return templates.TemplateResponse("shared_shares.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_short'),
        "user": user,
        "is_admin": True
    })


@router.get("/api/user/shares")
async def get_user_shares(request: Request):
    """获取用户分享列表API"""
    current_user = verify_user(request)
    
    conn = get_db_connection()
    shares = conn.execute("""
        SELECT ps.*, p.url, p.account, p.description
        FROM password_shares ps
        JOIN passwords p ON ps.password_id = p.id
        WHERE p.user_id = ?
        ORDER BY ps.created_at DESC
    """, (current_user['id'],)).fetchall()
    conn.close()
    
    return {"shares": rows_to_dict_list(shares)}


@router.get("/api/shares")
async def get_all_shares(request: Request):
    """获取所有分享列表API（管理员）"""
    verify_admin(request)
    
    conn = get_db_connection()
    shares = conn.execute("""
        SELECT ps.*, p.url, p.account, p.description, u.username as user_name
        FROM password_shares ps
        JOIN passwords p ON ps.password_id = p.id
        JOIN users u ON p.user_id = u.id
        ORDER BY ps.created_at DESC
    """).fetchall()
    conn.close()
    
    return {"shares": rows_to_dict_list(shares)}


@router.delete("/api/user/shares/{share_id}")
async def delete_user_share(request: Request, share_id: int):
    """删除用户分享API"""
    current_user = verify_user(request)
    
    conn = get_db_connection()
    
    # 检查分享是否存在且属于当前用户
    share_record = conn.execute("""
        SELECT ps.id, p.user_id, p.url
        FROM password_shares ps
        JOIN passwords p ON ps.password_id = p.id
        WHERE ps.id = ?
    """, (share_id,)).fetchone()
    
    if not share_record:
        conn.close()
        raise HTTPException(status_code=404, detail="分享记录不存在")
    
    if share_record['user_id'] != current_user['id']:
        conn.close()
        raise HTTPException(status_code=403, detail="无权删除此分享")
    
    # 删除分享记录
    cursor = conn.cursor()
    cursor.execute("DELETE FROM password_shares WHERE id = ?", (share_id,))
    conn.commit()
    conn.close()
    return {"message": "分享删除成功"}


@router.delete("/api/shares/{share_id}")
async def delete_share(request: Request, share_id: int):
    """删除分享API（管理员）"""
    verify_admin(request)
    
    conn = get_db_connection()
    
    # 检查分享是否存在并获取相关信息
    share_record = conn.execute("""
        SELECT ps.id, p.url
        FROM password_shares ps
        JOIN passwords p ON ps.password_id = p.id
        WHERE ps.id = ?
    """, (share_id,)).fetchone()
    if not share_record:
        conn.close()
        raise HTTPException(status_code=404, detail="分享记录不存在")
    
    # 删除分享记录
    cursor = conn.cursor()
    cursor.execute("DELETE FROM password_shares WHERE id = ?", (share_id,))
    conn.commit()
    conn.close()

    return {"message": "分享删除成功"}


@router.get("/api/user/shares/{share_id}/logs")
async def get_user_share_logs(request: Request, share_id: int):
    """获取用户分享访问日志API"""
    current_user = verify_user(request)
    
    conn = get_db_connection()
    
    # 检查分享是否存在且属于当前用户
    share_record = conn.execute("""
        SELECT ps.share_token, p.user_id
        FROM password_shares ps
        JOIN passwords p ON ps.password_id = p.id
        WHERE ps.id = ?
    """, (share_id,)).fetchone()
    
    if not share_record:
        conn.close()
        raise HTTPException(status_code=404, detail="分享记录不存在")
    
    if share_record['user_id'] != current_user['id']:
        conn.close()
        raise HTTPException(status_code=403, detail="无权查看此分享日志")
    
    # 获取访问日志
    logs = conn.execute("""
        SELECT * FROM access_logs
        WHERE share_token = ?
        ORDER BY accessed_at DESC
    """, (share_record['share_token'],)).fetchall()
    
    conn.close()
    
    return {"logs": rows_to_dict_list(logs)}


@router.get("/api/shares/{share_id}/logs")
async def get_share_logs(request: Request, share_id: int):
    """获取分享访问日志API（管理员）"""
    verify_admin(request)
    
    conn = get_db_connection()
    
    # 获取分享token
    share_record = conn.execute("SELECT share_token FROM password_shares WHERE id = ?", (share_id,)).fetchone()
    if not share_record:
        conn.close()
        raise HTTPException(status_code=404, detail="分享记录不存在")
    
    # 获取访问日志
    logs = conn.execute("""
        SELECT * FROM access_logs
        WHERE share_token = ?
        ORDER BY accessed_at DESC
    """, (share_record['share_token'],)).fetchall()
    
    conn.close()
    
    return {"logs": rows_to_dict_list(logs)}


@router.post("/api/shares")
async def create_share(
    request: Request,
    password_id: int = Form(...),
    access_password: str = Form(""),
    expires_hours: int = Form(0)
):
    """创建密码分享API"""
    current_user = verify_user(request)
    
    conn = get_db_connection()
    
    # 检查密码是否存在且属于当前用户
    password_record = conn.execute("SELECT id, user_id FROM passwords WHERE id = ?", (password_id,)).fetchone()
    if not password_record:
        conn.close()
        raise HTTPException(status_code=404, detail="密码记录不存在")
    
    if password_record['user_id'] != current_user['id']:
        conn.close()
        raise HTTPException(status_code=403, detail="无权分享此密码")
    
    # 生成分享token
    share_token = secrets.token_urlsafe(32)
    
    # 计算过期时间
    expires_at = None
    if expires_hours > 0:
        from datetime import timedelta
        expires_at = datetime.now() + timedelta(hours=expires_hours)
    
    # 处理访问密码
    access_password_hash = None
    if access_password:
        access_password_hash = hash_password(access_password)
    
    # 创建分享记录
    cursor = conn.cursor()
    cursor.execute("""
        INSERT INTO password_shares (password_id, share_token, access_password, expires_at)
        VALUES (?, ?, ?, ?)
    """, (password_id, share_token, access_password_hash, expires_at))
    
    share_id = cursor.lastrowid
    
    # 获取密码信息用于日志记录
    password_info = conn.execute("SELECT url FROM passwords WHERE id = ?", (password_id,)).fetchone()
    
    conn.commit()
    conn.close()
    
    # 生成分享链接
    share_url = f"/share/{share_token}"
    
    
    return {
        "message": "分享创建成功",
        "share_id": share_id,
        "share_url": share_url,
        "share_token": share_token
    }


@router.get("/share/{token}")
async def view_shared_password(request: Request, token: str):
    """查看分享的密码"""
    conn = get_db_connection()
    
    # 获取分享信息
    share_info = conn.execute("""
        SELECT ps.*, p.url, p.account, p.password, p.description
        FROM password_shares ps
        JOIN passwords p ON ps.password_id = p.id
        WHERE ps.share_token = ?
    """, (token,)).fetchone()
    
    if not share_info:
        conn.close()
        raise HTTPException(status_code=404, detail="分享链接不存在或已过期")
    
    # 检查是否过期
    if share_info['expires_at']:
        from datetime import datetime
        expires_at = datetime.fromisoformat(share_info['expires_at'])
        if datetime.now() > expires_at:
            conn.close()
            raise HTTPException(status_code=404, detail="分享链接已过期")
    
    # 如果设置了访问密码，检查会话中是否已验证
    if share_info['access_password']:
        verified_tokens = request.session.get('verified_share_tokens', [])
        if token not in verified_tokens:
            # 需要密码验证，跳转到密码输入页面
            conn.close()
            return templates.TemplateResponse("share_password_input.html", {
                "request": request,
                "app_name": config.get('DEFAULT', 'app_name'),
                "company_name": config.get('DEFAULT', 'company_short'),
                "share_token": token
            })
    
    # 记录访问日志
    client_ip = request.client.host
    user_agent = request.headers.get("user-agent", "")
    
    cursor = conn.cursor()
    cursor.execute("""
        INSERT INTO access_logs (share_token, ip_address, user_agent)
        VALUES (?, ?, ?)
    """, (token, client_ip, user_agent))
    
    # 更新访问次数
    cursor.execute("""
        UPDATE password_shares SET access_count = access_count + 1
        WHERE share_token = ?
    """, (token,))
    
    conn.commit()
    conn.close()
    
    share_dict = row_to_dict(share_info)
    
    return templates.TemplateResponse("shared_password.html", {
        "request": request,
        "app_name": config.get('DEFAULT', 'app_name'),
        "company_name": config.get('DEFAULT', 'company_short'),
        "password_info": share_dict
    })


@router.post("/share/{token}/verify")
async def verify_share_password(request: Request, token: str, access_password: str = Form(...)):
    """验证分享访问密码"""
    conn = get_db_connection()
    
    # 获取分享信息
    share_info = conn.execute("""
        SELECT access_password FROM password_shares WHERE share_token = ?
    """, (token,)).fetchone()
    
    if not share_info:
        conn.close()
        raise HTTPException(status_code=404, detail="分享链接不存在")
    
    # 验证密码
    if not share_info['access_password'] or not secrets.compare_digest(
        hash_password(access_password), share_info['access_password']
    ):
        conn.close()
        return templates.TemplateResponse("share_password_input.html", {
            "request": request,
            "app_name": config.get('DEFAULT', 'app_name'),
            "company_name": config.get('DEFAULT', 'company_short'),
            "share_token": token,
            "error": "访问密码错误"
        })
    
    conn.close()
    
    # 密码验证成功，将token添加到会话中
    if 'verified_share_tokens' not in request.session:
        request.session['verified_share_tokens'] = []
    request.session['verified_share_tokens'].append(token)
    
    # 重定向到分享页面
    return RedirectResponse(url=f"/share/{token}", status_code=302)